Ext.onReady(function() {
	Ext.SSL_SECURE_URL = "../../ext-3.2.1/resources/images/default/s.gif";
	Ext.BLANK_IMAGE_URL = "../../ext-3.2.1/resources/images/default/s.gif";
	Ext.QuickTips.init();
	Ext.form.Field.prototype.msgTarget = 'side';
	var pageSize = 20;
	// tab页面
    var centerTabPanel = new Ext.TabPanel({
        region : 'center',
        deferredRender : false,
        activeTab : 1,
        margins : '0 5 0 0',
        id:'centerTabPanelPro',
       // plugins : new Ext.ux.TabCloseMenu(),
        resizeTabs : false,
        minTabWidth : 50,
        //tabWidth : 230,

        enableTabScroll : true,
        autoScroll : true,
         items:[{
            title: '下级标签：',
           // tabWidth:120,
           iconCls: 'tabsDown',
          //contentEl:'grid-div',
            disabled:true
           // autoScroll:true
        },
          {
            title: '病历信息管理',
            iconCls: 'tabs',
             //tabWidth:150,
            contentEl:'grid-div',
            autoScroll:true
        }],
        loadPage : function(href, cls, title) {
    
            var tabId = 'workPanel' + cls;
            var tab = this.getComponent(tabId);
            if (tab) {
                this.setActiveTab(tab);
            } else {
                var autoLoad = {
                    url : href,
                    scripts : true
                };
                var p = this.add(new DocPanel({
                    id : tabId,
                    cclass : cls,
                    layout : 'fit',
                    items : [new IFrameComponent({
                        id : tabId,
                        url : href
                    })],
                    title : title,
                    iconCls : 'tabs'
                }));
                this.setActiveTab(p);
            }
        }
    });
    IFrameComponent = Ext.extend(Ext.BoxComponent, {
        onRender : function(ct, position) {
            this.el = ct.createChild({
                tag : 'iframe',
                id : 'iframe-' + this.id,
                frameBorder : 0,
                src : this.url
            });
        }
    });
    DocPanel = Ext.extend(Ext.Panel, {
        closable : true,
        autoScroll : true,
        initComponent : function() {
            DocPanel.superclass.initComponent.call(this);
        },
        scrollToMember : function(member) {
            var el = Ext.fly(this.cclass + '-' + member);
            if (el) {
                var top = (el.getOffsetsTo(this.body)[1])
                        + this.body.dom.scrollTop;
                this.body.scrollTo('top', top - 25, {
                    duration : .75,
                    callback : this.hlMember.createDelegate(this, [member])
                });
            }
        },
        scrollToSection : function(id) {
            var el = Ext.getDom(id);
            if (el) {
                var top = (Ext.fly(el).getOffsetsTo(this.body)[1])
                        + this.body.dom.scrollTop;
                this.body.scrollTo('top', top - 25, {
                    duration : .5,
                    callback : function() {
                        Ext.fly(el).next('h2').pause(.2).highlight('#8DB2E3', {
                            attr : 'color'
                        });
                    }
                });
            }
        },
        hlMember : function(member) {
            var el = Ext.fly(this.cclass + '-' + member);
            if (el) {
                el.up('tr').highlight('#cadaf9');
            }
        }
    });
 	var d = new Date();
	d.setTime(d.getTime() - 30 * 24 * 3600 * 1000);
     var starDate = new  Ext.form.DateField({
	     id:'date1',
	     format:'Y-m-d',
	     editable : false,
	     allowBlank : false,
	     value : d
     });
     
      var endDate = new  Ext.form.DateField({
	      id:'date2',
	      format:'Y-m-d',
	      allowBlank : false,
	      editable : false,
	 	  value : new Date().format("Y-m-d")
      });
		//科室
	var departStore_child = new Ext.data.Store({
		proxy : new Ext.data.ScriptTagProxy({
			url : '../../tiCase/loadDepartMent.action'
		}),
		fields : ['value', 'label'],
		reader : new Ext.data.ArrayReader({}, [{
			name : 'value',
			type : 'string'
		}, {
			name : 'label',
			type : 'string'
		}]),
		remoteSort : false
	});
	departStore_child.load();
	var departCombox_child = new Ext.form.ComboBox({
		store : departStore_child,
		displayField : 'label',
		hiddenName : 'districtStore_child',
		valueField : 'value',
		typeAhead : true,
		editable : false,
		mode : 'local',
		triggerAction : 'all',
		selectOnFocus : true,
		width : 120
	});
	
	new Ext.Viewport({
		region : 'center',
		layout : 'fit',
		items : centerTabPanel
	});
	var queryButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/query.png",
		id : 'queryButton',
		cls : 'x-btn-text-icon',
		text : '查询',
		tooltip : '查询记录',
		handler : onQueryClick
	});

	var addButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/add.png",
		id : 'addButton',
		cls : 'x-btn-text-icon',
		text : '处理',
		// disabled:true,
		handler : onAddClick
	});
	var viewButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/edit.png",
		id : 'viewButton',
		cls : 'x-btn-text-icon',
		text : '查看',
		// disabled:true,
		tooltip : '查看一条选中记录。',
		handler : onViewClick
	});
	var delButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/del.png",
		id : 'delButton',
		cls : 'x-btn-text-icon',
		text : '删除',
		// disabled:true,
		tooltip : '删除已选中的记录。',
		handler : onDelClick
	});
		
	 //显示操作按钮
	function renderBtn_inputMember(val, p, record) {
		var contentId = Ext.id();
		createGridButton.defer(1, this, [1, "病历信息维护", contentId, record]);
		return ('<div id="' + contentId + '"></div>');
	}
	function format_sex(value) {
        if (value == '1') return "男";
        else if (value == '2') return "女";
        else return '';
    }
    function format_read(value) {
        if (value == '1') return "已处理";
        else if (value == '2') return "未处理";
        else return '';
    }
    function  format_marry(value){
        if (value == '0') return "未婚";
        else if (value == '1') return "已婚";
        else return '';
    }
	// 通用的列表中按钮生成函数
	function createGridButton(index, value, contentid, record) {
		if (index == 1) {
			if(document.getElementById(contentid)) {
				new Ext.Button({
					renderTo : contentid,
					text : "病历信息维护",
					handler : function(btn, e) {
						var ridStr = record.id;
						centerTabPanel.loadPage('districtList6_child.jsp?pid='+ridStr, ridStr, value);
					},
					cls : 'x-btn-text',
					scope : this
				});
			}
		}
	}	
		
	function onViewClick(){
		var selectedCount = sm.getCount();
		if (selectedCount == 0) {
			Ext.Msg.alert('查看记录', '未选中任何一条记录，请选择要查看的记录！');
			return;
		} else if (selectedCount > 1) {
			Ext.Msg.alert('查看记录', '只能选择一条记录，不能同时选择多条记录！');
			return;
		}
		record = sm.getSelected();
		id = record.id;
		centerTabPanel.loadPage(encodeURI("../../tiCase/onViewPage.action?caseId="+ id), 'modify', '病历查看');
	}

	var gridStore = new Ext.data.Store({
		proxy : new Ext.data.ScriptTagProxy({
			url : encodeURI('../../tiCase/searchMember.action')
		}),
		reader : new Ext.data.JsonReader({
			root : 'results',
			totalProperty : 'total',
			id : 'id'
		}, [{
			name : 'name',
			mapping : 'name'
		}, {
			name : 'sex',
			mapping : 'sex'
		}, {
			name : 'birthday',
			mapping : 'birthday'
		}, {
			name : 'age',
			mapping : 'age'
		}, {
			name : 'bornPlace',
			mapping : 'bornPlace'
		}, {name: 'homeTown', mapping: 'homeTown'}
		,  {name: 'marriage', mapping: 'marriage'},
		  {name: 'idcard', mapping: 'idcard'},
		  {name: 'profession', mapping: 'profession'},
		   {name: 'nowAddress', mapping: 'nowAddress'} ,
		   {name: 'homeAddress', mapping: 'homeAddress'},
		   {name: 'workAddress', mapping: 'workAddress'},
		    {name: 'tel', mapping: 'tel'},
		    {name: 'realFileName', mapping: 'realFileName'},
		    {name: 'imgsrc', mapping: 'imgsrc'},
		     {name: 'isRead', mapping: 'isRead'}
		]),
		remoteSort : false
	});

	var sm = new Ext.grid.CheckboxSelectionModel();

	var cm = new Ext.ux.grid.LockingColumnModel([sm, {id: 'id',
        header: "主键",
        dataIndex: 'id',
        width: 60,
        sortable: true,
        hidden:true
     
    }, {
		id : 'name',
		header : "真实姓名",
		dataIndex : 'name',
		width : 80,
		align : 'center',
		sortable : false,
		locked : false,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}, {
		id : 'sex',
		header : "性别",
		dataIndex : 'sex',
		width : 40,
		align : 'center',
		sortable : false,
		renderer : format_sex
	}, {
		id : 'birthday',
		header : "出生日期",
		dataIndex : 'birthday',
		align : 'center',
		width : 100,
		sortable : false,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}, {
		id : 'age',
		header : "年龄",
		dataIndex : 'age',
		align : 'center',
		width : 40,
		sortable : false,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	},{
		id : 'bornPlace',
		header : "出生地",
		dataIndex : 'bornPlace',
		align : 'center',
		width : 200,
		sortable : false,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	},
       {
            id: 'homeTown',
            header: "籍贯",
            dataIndex: 'homeTown',
            align:'center',
            width : 200,
            sortable: false
        },
       {
            id: 'marriage',
            header: "婚姻",
            dataIndex: 'marriage',
            align:'center',
            width : 60,
            sortable: false,
            renderer:format_marry
        },{
            id: 'realFileName',
            header: "附  件",
            dataIndex: 'realFileName',
            renderer : function format_totalAll1(value, cellmeta, record, rowIndex, columnIndex, store){
            	if(value!='')
                	return '<a title="点击下载" href="../../tiCase/downloadFile.action?rid='+record.id+'">'+value+'</a>';
               		return '';
                },
            align:'center',
            width : 200,
            sortable: false
        },
       {
            id: 'idcard',
            header: "身份证",
            dataIndex: 'idcard',
            align:'center',
            width : 150,
            sortable: false
          
        },
       {
            id: 'profession',
            header: "职业",
            dataIndex: 'profession',
            align:'center',
            width : 120,
            sortable: false
        },
       {
            id: 'nowAddress',
            header: "现住地址",
            dataIndex: 'nowAddress',
            align:'center',
            width : 200,
            sortable: false
        },
       {
            id: 'homeAddress',
            header: "户口地址",
            dataIndex: 'homeAddress',
            align:'center',
            width : 200,
            sortable: false
        },
       {
            id: 'workAddress',
            header: "工作单位",
            dataIndex: 'workAddress',
            width : 200,
            align:'center',
            sortable: false
        },
       {
            id: 'tel',
            header: "电话",
            dataIndex: 'tel',
            width : 120,
            align:'center',
            sortable: false
        }
        ,
       {
            id: 'isRead',
            header: "处理状态",
            dataIndex: 'isRead',
            width : 80,
            align:'center',
            sortable: false,
            renderer:format_read
          
        }
	]);
	

	var grid = new Ext.ux.grid.SSNJLOCKPAGEGrid({
		// el:'grid-div',
		id : 'grid',
		layout : 'fit',
		store : gridStore,
		loadMask : {
			msg : '正在加载数据，请稍候……'
		},
		cm : cm,
		height : gridHeight,
		sm : sm,
		viewConfig : {
			enableRowBody : false

		},
		bodyStyle : 'width:100%;',
		tbar : ['-','创建日期:',starDate,'-至-',endDate,'-','科室：',departCombox_child,'-',queryButton,'-',viewButton,'-',addButton,'-',delButton,'-'],
		frame : false,
		border : false,
		stripeRows : true
			// bbar:pagingToolbar
	});
	grid.render(Ext.get('grid-div'));
	gridStore.load({params:{start:0, limit:pageSize}});

	function onAddClick() {
			  var selectedCount = sm.getCount();
        if (selectedCount == 0) {
            Ext.Msg.alert('处理操作', '未选中任何一条记录，请选择要操作的人员！');
            return;
        } else if (selectedCount > 1) {
            Ext.Msg.alert('处理操作', '只能选择一个人员，不能同时选择多个人员！');
            return;
        } else {
            var record = sm.getSelected();
            var id = record.id;
             if (gridStore.getById(id).data['isRead'] == '1') {
                Ext.Msg.alert('处理操作', '此人状态已处理，不能进行再处理操作！');
                return;
            } else {
                Ext.MessageBox.wait('正在处理，请稍等...');
                Ext.Ajax.request({
                    url:  '../../tiCase/operRead.action',
                    failure: function(result, request) {
                        Ext.MessageBox.hide();
                        Ext.Msg.show({
                            title: '错误',
                            msg: '<span style="text-align:center;width:250px;margin:5 0 5 0;">' + '处理操作失败！' + '</span>',
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.WARNING
                        });

                    },
                    success: function(result, request) {
                        Ext.MessageBox.hide();
                        Ext.Msg.show({
                            title: '成功',
                            msg: '<span style="text-align:center;width:250px;margin:5 0 5 0;">' + '处理操作成功！' + '</span>',
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                        });

                        gridStore.reload();
                    },
                    params: { id: id,flag:1}
                });
            }
        }
	}
	
	function onModClick() {
	    var selectedCount = sm.getCount();
		if (selectedCount == 0) {
			Ext.Msg.alert('修改记录', '未选中任何一条记录，请选择要修改的记录！');
			return;
		} else if (selectedCount > 1) {
			Ext.Msg.alert('修改记录', '只能选择一条记录，不能同时选择多条记录！');
			return;
		}
		record = sm.getSelected();
		centerTabPanel.loadPage(encodeURI("../../tiCase/loadCase.action?caseId="+ record.id), 2, "病历修改");
	}

	function startWith(str1, str2) {
		if (str2 == null || str2 == "" || str1.length == 0
				|| str2.length > str1.length)
			return false;
		if (str1.substr(0, str2.length) == str2)
			return true;
		else
			return false;
	}

	function onDelClick(item) {
		  var selectedCount = sm.getCount();
        if (selectedCount == 0) {
            Ext.Msg.alert('删除操作', '未选中要删除的数据，请选择要删除的数据！');
            return;
        } else { 
             var records = sm.getSelections();
            var _ids = '';
          
            Ext.Msg.confirm('删除记录', '请确认要删除记录吗?按是将删除选中记录！', function(btn) {
                if (btn == 'yes') {
                    var records = sm.getSelections();
                    var _ids = '';
                    for (var i = 0; i < records.length; i++) {
                        _ids += records[i].id;
                        _ids += '_';
                    }
                    Ext.MessageBox.wait('正在处理，请稍等...');
                    Ext.Ajax.request({
                        url:  '../../tiCase/delTiCase.action',
                        failure: function(result, request) {
                            Ext.MessageBox.hide();
                            Ext.Msg.show({
                                title: '错误',
                                msg: '<span style="text-align:center;width:250px;margin:5 0 5 0;">' + '删除失败！' + '</span>',
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.WARNING
                            });
                        },
                        success: function(result, request) {
                            Ext.MessageBox.hide();
                            Ext.Msg.show({
                                title: '成功',
                                msg: '<span style="text-align:center;width:250px;margin:5 0 5 0;">' + '删除成功！' + '</span>',
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.INFO
                            });
                             gridStore.reload();
                            
                        },
                        params: { deleteID: _ids}
                    });
                }
            });
        }
	}
	function onQueryClick(item) {
	    var statrValue = starDate.getRawValue();
	    if(statrValue==null || statrValue=="")
	    {
	        alert('请选择开始时间');
	        return;
	    }
	    var entDateValue = endDate.getRawValue();
	    if(entDateValue==null || entDateValue=="")
	    {
	        alert('请选择结束时间');
	        return;
	    }
	    var devale=   departCombox_child.getValue();
	    if(devale=="")
	    {
	      alert('请选择科室');
	      return;
	    }
		gridStore.proxy = new Ext.data.ScriptTagProxy({
			url : encodeURI('../../tiCase/searchMember.action?dpartId='
					+devale+"&startTime="+statrValue+"&endTime="+entDateValue)
		});
		gridStore.reload({
			params : {
				start : 0,
				limit : pageSize
			}
		});
	}
})
